package com.toefl.speaking.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.toefl.speaking.business.QuestionBusiness;
import com.toefl.speaking.dao.bean.QuestionBean;

import android.os.Environment;
import android.util.Log;

public class AppUtils {

	private static final String USER_AGENT = "User-Agent";
	public static String CTSSID = "cb27df02-ac3b-4b9a-aa1a-912b457bc68a";

	public static String doGet(String url, boolean isDownload) {
		String result = null;
		HttpClient httpclient = new DefaultHttpClient();
		// httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * 1000);
		// httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5 * 1000);
		HttpGet httpGet;
		httpGet = new HttpGet(url);
		httpGet.setHeader(USER_AGENT, "cracking_toefl_speaking/1.0(android-2.x)");
		httpGet.setHeader("Cookie", "CTSSID=" + CTSSID);

		try {
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() != 404) {
				if (isDownload) {
					InputStream inputStream = httpResponse.getEntity().getContent();
					ByteArrayOutputStream outStream = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len1 = 0;
					while ((len1 = inputStream.read(buffer)) != -1) {
						outStream.write(buffer, 0, len1);
					}
					byte[] resultByte = outStream.toByteArray();
					String[] urlSplit = url.split("/");
					if (!new File(Environment.getExternalStorageDirectory().getAbsolutePath()
							+ AppConstans.PROJECT_PATH + AppConstans.ADUIO_PATH).exists()) {
						File temp = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
								+ AppConstans.PROJECT_PATH + AppConstans.ADUIO_PATH);
						temp.mkdirs();
					}
					File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
							+ AppConstans.PROJECT_PATH + AppConstans.ADUIO_PATH);
					File file = new File(dir, urlSplit[urlSplit.length - 1] + ".mp3");
					QuestionBean temp = QuestionBusiness.getQuestionInfoByQID(String
							.valueOf(urlSplit[urlSplit.length - 1]));
					QuestionBean updateQuestion = new QuestionBean();
					updateQuestion.question_id = Integer.parseInt(urlSplit[urlSplit.length - 1]);
					updateQuestion.question_listent_path = file.getAbsolutePath();
					QuestionBusiness.updateCustomer(updateQuestion);

					FileOutputStream fileOutputStream = new FileOutputStream(file);
					fileOutputStream.write(resultByte);
					fileOutputStream.flush();
					return null;
				}
				result = EntityUtils.toString(httpResponse.getEntity());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String doGet(String url) {
		return doGet(url, false);
	}

	public static String doPost(String url, List<NameValuePair> nameValuePairs) {

		String result = null;
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * 1000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5 * 1000);
		HttpPost httppost;
		httppost = new HttpPost(url);
		httppost.setHeader(USER_AGENT, "cracking_toefl_speaking/1.0(android-2.x)");
		httppost.setHeader("Cookie", "CTSSID=" + CTSSID);
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() != 404) {
				result = EntityUtils.toString(response.getEntity());
				Header header = response.getFirstHeader("Set-Cookie");
				if (header != null) {
					String cookie = header.getValue();
					if (cookie != null) {
						String[] cookieItem = cookie.split(";");
						Map<String, String> cookieMap = new HashMap<String, String>();
						for (int i = 0; i < cookieItem.length; i++) {
							String[] temp = cookieItem[i].split("=");
							if ("".equals(temp[1]))
								cookieMap.put(temp[0], temp[1]);
						}
						CTSSID = cookieMap.get("CTSSID");
						Log.i("11111111111111111111111", CTSSID);
					}
				}

			}

		} catch (Exception e) {
			Log.e("HttpUtils", "连接服务器出错");
			e.printStackTrace();
		}
		return result;
	}

	public static String doPostWithFile(String url, File uploadFile) {

		String result = null;
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5 * 1000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5 * 1000);
		HttpPost httppost;
		httppost = new HttpPost(url);
		httppost.setHeader(USER_AGENT, "cracking_toefl_speaking/1.0(android-2.x)");
		httppost.setHeader("Cookie", "CTSSID=" + CTSSID);
		try {
			MultipartEntity mpEntity = new MultipartEntity();
			FileBody file = new FileBody(uploadFile);
			mpEntity.addPart("UserFile", file);
			httppost.setEntity(mpEntity);
			HttpResponse response = httpclient.execute(httppost);
			if (response.getStatusLine().getStatusCode() != 404) {
				result = EntityUtils.toString(response.getEntity());
			}

		} catch (Exception e) {
			Log.e("HttpUtils", "连接服务器出错");
			e.printStackTrace();
		}
		return result;
	}

	public static String httpPost(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException,
			IOException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		// Your DATA
		// nameValuePairs.add(new BasicNameValuePair("id", "12345"));
		// nameValuePairs.add(new BasicNameValuePair("stringdata",
		// "eoeAndroid.com is Cool!"));

		httpPost.setHeader(USER_AGENT, "cracking_toefl_speaking/1.0(android)");

		String result = null;
		HttpEntity httpEntity = null;
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httpPost);

			if (response.getStatusLine().getStatusCode() != 404) {
				result = EntityUtils.toString(response.getEntity());
				Header[] a = response.getAllHeaders();
			}

			httpEntity = httpclient.execute(httpPost).getEntity();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			httpPost.abort();
		}
		// return result;
		if (httpEntity == null) {
			return null;
		}
		return retrieveHttpEntity(httpEntity);
	}

	private static String retrieveHttpEntity(HttpEntity httpEntity) throws UnsupportedEncodingException,
			IllegalStateException, IOException {
		StringBuffer stringBuffer = new StringBuffer();
		InputStreamReader is = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
		BufferedReader bufferedReader = new BufferedReader(is);
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			stringBuffer.append(line);
		}
		return stringBuffer.toString();
	}
}
